Python中的list(), dict(), [], {} |
您所在的位置:网站首页 › python list dict转换 › Python中的list(), dict(), [], {} |
文章作者:Tyan 博客:noahsnail.com | CSDN | 简书 0. 测试环境Python 3.6.9 1. 引言在Python中,list,dict作为Python的基础数据结构,经常会用到,其定义形式通常有下面两种: a = [] b = list() c = {} d = dict()二者有什么区别呢? 2. list() vs [],dict() vs {}运行时间首先比较一下二者的运行时间,timeit模块主要用来测量Python小段代码的执行时间,默认执行100万次。代码如下: >>> from timeit import timeit >>> timeit('[]') 0.05389202758669853 >>> timeit('list()') 0.1250211838632822 >>> timeit('{}') 0.06583642773330212 >>> timeit('dict()') 0.1366278938949108 >>> type({})从时间上来看,明显[]与{}的定义形式更快。 数据类型转换>>> a = (1, 2, 3) >>> b = [a] >>> c = list(a) >>> b [(1, 2, 3)] >>> c [1, 2, 3] >>> s = 'abc' >>> x = [s] >>> y = list(s) >>> x ['abc'] >>> y ['a', 'b', 'c']从上面的代码可以看出,list()除了可以定义之外,还可以对将其它数据类型转换为list,而[]则没有数据类型转换的功能。 3. 为什么[]比list()更快dis库是Python自带的一个库,可以用来分析字节码,而字节码是CPython解释器的实现细节。[],list()的字节码对比如下: >>> import dis >>> dis.dis(lambda : []) 1 0 BUILD_LIST 0 2 RETURN_VALUE >>> dis.dis(lambda : list()) 1 0 LOAD_GLOBAL 0 (list) 2 CALL_FUNCTION 0 4 RETURN_VALUE从上面的代码可以看出,list()有符号查找和函数调用的开销,因此其速度更慢。 4. 总结[],{}定义数据类型速度更快,list(),dict()除了能定义数据类型之外,还可以对数据进行类型转换。 References1.https://stackoverflow.com/questions/5790860/and-vs-list-and-dict-which-is-better 2.https://www.quora.com/In-Python-any-difference-between-using-and-list-or-between-and-dict 3.https://docs.python.org/zh-cn/3/library/timeit.html 4.https://docs.python.org/zh-cn/3/library/dis.html 5.https://stackoverflow.com/questions/30216000/why-is-faster-than-list |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |